import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useChatStore = defineStore('chat', () => {
  const conversations = ref([])
  const currentConversation = ref(null)
  const messages = ref([])
  const socket = ref(null)
  const isConnected = ref(false)
  const onlineUsers = ref([])

  // 统一消息结构
  const normalizeMessage = (raw) => {
    if (!raw) return raw
    const timestamp = raw.timestamp
      ? (typeof raw.timestamp === 'number' ? raw.timestamp : new Date(raw.timestamp).getTime())
      : (raw.createdAt ? new Date(raw.createdAt).getTime() : Date.now())
    return {
      id: raw.id,
      conversationId: raw.conversationId,
      senderId: raw.senderId,
      receiverId: raw.receiverId,
      type: raw.type, // PRIVATE / GROUP
      contentType: raw.contentType,
      content: raw.content,
      status: raw.status,
      timestamp
    }
  }

  // WebSocket 连接
  const connectWebSocket = (token) => {
    console.log('开始连接WebSocket，token:', token ? '已提供' : '未提供')
    
    if (socket.value) {
      socket.value.close()
    }

    const wsUrl = import.meta.env.VITE_WS_URL || 'ws://localhost:9090/ws'
    console.log('连接WebSocket地址:', wsUrl)
    socket.value = new WebSocket(wsUrl)

    socket.value.onopen = () => {
      console.log('WebSocket 连接已建立')
      isConnected.value = true
      
      // 发送认证消息
      const authMessage = {
        type: 'AUTH',
        data: {
          token: token
        }
      }
      console.log('发送认证消息:', authMessage)
      socket.value.send(JSON.stringify(authMessage))
    }

    socket.value.onmessage = (event) => {
      const data = JSON.parse(event.data)
      console.log('收到消息:', data)
      
      handleWebSocketMessage(data)
    }

    socket.value.onclose = (event) => {
      console.log('WebSocket 连接已关闭, code:', event.code, 'reason:', event.reason)
      isConnected.value = false
      
      // 只有在非正常关闭时才重连
      if (event.code !== 1000) {
        console.log('3秒后尝试重连...')
        setTimeout(() => {
          if (!isConnected.value) {
            console.log('开始重连WebSocket')
            connectWebSocket(token)
          }
        }, 3000)
      }
    }

    socket.value.onerror = (error) => {
      console.error('WebSocket 错误:', error)
      isConnected.value = false
    }
  }

  // 处理 WebSocket 消息
  const handleWebSocketMessage = (data) => {
    console.log('收到WebSocket消息:', data)
    
    switch (data.type) {
      case 'AUTH_RESPONSE':
        console.log('认证响应:', data.data)
        if (data.data.success) {
          console.log('WebSocket认证成功')
        }
        break
      case 'MESSAGE':
        addMessage(normalizeMessage(data.data))
        break
      case 'MESSAGE_ACK':
        console.log('消息发送确认:', data.data)
        break
      case 'STATUS':
        updateUserStatus(data.data)
        break
      case 'CONVERSATION_LIST':
        conversations.value = data.data
        break
      case 'MESSAGE_HISTORY':
        messages.value = data.data
        break
      case 'ERROR':
        console.error('WebSocket错误:', data.data.message)
        break
      default:
        console.log('未知消息类型:', data.type)
    }
  }

  // 添加消息
  const addMessage = (message) => {
    const msg = normalizeMessage(message)
    messages.value.push(msg)
    
    // 更新对话列表中的最后一条消息
    let conversation = conversations.value.find(c => (c.id === msg.conversationId || c.clientId === msg.conversationId))

    // 兼容不同会话ID格式：找不到则按 PRIVATE/GROUP 的目标ID回退匹配
    if (!conversation) {
      try {
        const user = JSON.parse(localStorage.getItem('user') || 'null')
        const currentUserId = user?.id
        if (msg.type === 'PRIVATE' && currentUserId) {
          // 兼容 private_a_b 格式：优先匹配 clientId
          if (typeof msg.conversationId === 'string' && msg.conversationId.startsWith('private_')) {
            conversation = conversations.value.find(c => c.clientId === msg.conversationId)
          }
          if (!conversation) {
            const otherUserId = Number(msg.senderId) === Number(currentUserId) ? msg.receiverId : msg.senderId
            conversation = conversations.value.find(c => c.type === 'PRIVATE' && Number(c.targetId) === Number(otherUserId))
          }
        } else if (msg.type === 'GROUP') {
          if (typeof msg.conversationId === 'string' && msg.conversationId.startsWith('group_')) {
            conversation = conversations.value.find(c => c.clientId === msg.conversationId || c.id === msg.conversationId)
          }
          if (!conversation) {
            conversation = conversations.value.find(c => c.type === 'GROUP' && Number(c.targetId) === Number(msg.receiverId))
          }
        }
      } catch (e) {
        // ignore
      }
    }

    if (conversation) {
      conversation.lastMessage = (typeof msg.content === 'string')
        ? (safeGetText(msg.content))
        : (safeGetText(JSON.stringify(msg.content)))
      conversation.lastMessageTime = msg.timestamp
      // 只有当收到的消息不属于当前打开的会话时，才增加未读数
      if (!currentConversation.value || currentConversation.value.id !== conversation.id) {
        conversation.unreadCount = (conversation.unreadCount || 0) + 1
      }
    }
  }

  const safeGetText = (raw) => {
    if (raw == null) return ''
    try {
      const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw
      if (parsed && typeof parsed === 'object' && parsed.text) return parsed.text
      return typeof raw === 'string' ? raw : JSON.stringify(raw)
    } catch (e) {
      return String(raw)
    }
  }

  // 更新用户状态
  const updateUserStatus = (statusData) => {
    const userIndex = onlineUsers.value.findIndex(u => u.id === statusData.userId)
    if (userIndex >= 0) {
      onlineUsers.value[userIndex].status = statusData.status
    } else if (statusData.status === 'ONLINE') {
      onlineUsers.value.push({
        id: statusData.userId,
        status: statusData.status
      })
    }
  }

  // 发送消息
  const sendMessage = (messageData) => {
    console.log('尝试发送消息:', messageData)
    console.log('WebSocket状态 - socket存在:', !!socket.value, '已连接:', isConnected.value)
    
    if (!socket.value || !isConnected.value) {
      console.error('WebSocket未连接，尝试重新连接...')
      const token = localStorage.getItem('token')
      if (token) {
        connectWebSocket(token)
        // 等待连接建立后再发送消息
        setTimeout(() => {
          if (isConnected.value) {
            sendMessage(messageData)
          } else {
            console.error('重连失败，无法发送消息')
            alert('网络连接异常，请刷新页面重试')
          }
        }, 2000)
      } else {
        console.error('没有token，无法连接WebSocket')
        alert('登录状态异常，请重新登录')
      }
      return
    }

    // 直接使用传入的参数，而不是从conversationId解析
    const receiverId = messageData.receiverId
    const chatType = messageData.conversationType
    const contentType = messageData.contentType || 'TEXT'
    const content = messageData.content

    if (!receiverId || !chatType) {
      console.error('缺少必要的参数：receiverId或chatType')
      return
    }
    
    const payloadContent = (contentType || 'TEXT') === 'TEXT'
      ? { text: String(content || '') }
      : content

    const message = {
      type: 'MESSAGE',
      data: {
        receiverId: receiverId,
        chatType: chatType,
        contentType: contentType,
        content: payloadContent
      }
    }
    
    console.log('发送WebSocket消息:', message)
    try {
      socket.value.send(JSON.stringify(message))
      console.log('消息发送成功')
    } catch (error) {
      console.error('发送消息失败:', error)
      alert('发送消息失败，请重试')
    }
  }

  // 加载对话列表
  const loadConversations = async () => {
    try {
      const { getConversations } = await import('../api/chat.js')
      const conversationList = await getConversations()
      const me = (() => { try { return JSON.parse(localStorage.getItem('user') || 'null')?.id } catch { return null } })()
      conversations.value = (conversationList || []).map(c => {
        let normalizedId = c.clientId || c.id
        if (!normalizedId) {
          if (c.type === 'PRIVATE' && me && c.targetId) {
            const a = Math.min(Number(me), Number(c.targetId))
            const b = Math.max(Number(me), Number(c.targetId))
            normalizedId = `private_${a}_${b}`
          } else if (c.type === 'GROUP' && c.targetId) {
            normalizedId = `group_${c.targetId}`
          }
        }
        return { ...c, id: normalizedId }
      })
      console.log('加载会话列表:', conversations.value.length, '个会话')

      // 加载每个会话的最新一条消息（仅对缺少摘要的会话进行补全）
      await refreshConversationsSummaries()
    } catch (error) {
      console.error('加载会话列表失败:', error)
      conversations.value = []
    }
  }

  // 补全会话的最后一条消息与时间，避免刷新后摘要为空或不准确
  const refreshConversationsSummaries = async () => {
    const { getPrivateMessages, getGroupMessages } = await import('../api/chat.js')
    const tasks = conversations.value
      .filter(conv => !conv.lastMessageTime && !conv.lastTime)
      .map(async (conv) => {
        try {
          if (conv.type === 'PRIVATE') {
            const targetUserId = conv.targetId
            const res = await getPrivateMessages(targetUserId, { page: 1, size: 1 })
            const latest = Array.isArray(res) && res.length ? normalizeMessage(res[0]) : null
            if (latest) {
              conv.lastMessage = safeGetText(latest.content)
              conv.lastMessageTime = latest.timestamp
            }
          } else if (conv.type === 'GROUP') {
            const groupId = conv.targetId
            const res = await getGroupMessages(groupId, { page: 1, size: 1 })
            const latest = Array.isArray(res) && res.length ? normalizeMessage(res[0]) : null
            if (latest) {
              conv.lastMessage = safeGetText(latest.content)
              conv.lastMessageTime = latest.timestamp
            }
          }
        } catch (e) {
          // 忽略单个会话失败，继续其他
          console.warn('补全会话摘要失败:', conv, e)
        }
      })
    await Promise.all(tasks)
  }

  // 加载消息历史
  const loadMessageHistory = (conversationId, page = 1, size = 20) => {
    if (socket.value && isConnected.value) {
      socket.value.send(JSON.stringify({
        type: 'GET_MESSAGE_HISTORY',
        data: {
          conversationId,
          page,
          size
        }
      }))
    }
  }

  // 设置当前对话
  const setCurrentConversation = async (conversation) => {
    currentConversation.value = conversation
    messages.value = []
    
    if (conversation) {
      // 加载历史消息
      await loadHistoryMessages(conversation)
      // 标记会话为已读（后端重置未读计数）
      try {
        const { markConversationAsRead } = await import('../api/chat.js')
        await markConversationAsRead(conversation.id)
      } catch (e) {
        console.error('标记会话为已读失败:', e)
      }
      // 本地重置未读计数
      markMessagesAsRead(conversation.id)
    }
  }

  // 通过HTTP API加载历史消息
  const loadHistoryMessages = async (conversation) => {
    try {
      let historyMessages = []
      
      if (conversation.type === 'PRIVATE') {
        // 私聊消息：从conversationId中解析出对方用户ID
        const targetUserId = conversation.targetId || conversation.id.replace('private_', '')
        const { getPrivateMessages } = await import('../api/chat.js')
        historyMessages = await getPrivateMessages(targetUserId)
      } else if (conversation.type === 'GROUP') {
        // 群聊消息
        const groupId = conversation.targetId || conversation.id.replace('group_', '')
        const { getGroupMessages } = await import('../api/chat.js')
        historyMessages = await getGroupMessages(groupId)
      }
      
      // 设置历史消息
      messages.value = (historyMessages || []).map(normalizeMessage)
      if (messages.value.length) {
        const last = messages.value[messages.value.length - 1]
        const conv = conversations.value.find(c => c.id === (conversation.id))
        if (conv) {
          conv.lastMessage = safeGetText(last.content)
          conv.lastMessageTime = last.timestamp
        }
      }
      console.log('加载历史消息:', messages.value.length, '条')
      
    } catch (error) {
      console.error('加载历史消息失败:', error)
      messages.value = []
    }
  }

  // 标记消息为已读
  const markMessagesAsRead = (conversationId) => {
    if (socket.value && isConnected.value) {
      socket.value.send(JSON.stringify({
        type: 'MARK_AS_READ',
        data: { conversationId }
      }))
    }
    
    // 更新本地未读计数
    const conversation = conversations.value.find(c => c.id === conversationId)
    if (conversation) {
      conversation.unreadCount = 0
    }
  }

  // 断开连接
  const disconnect = () => {
    if (socket.value) {
      socket.value.close()
      socket.value = null
    }
    isConnected.value = false
  }

  // 计算属性
  const totalUnreadCount = computed(() => {
    return conversations.value.reduce((total, conv) => total + (conv.unreadCount || 0), 0)
  })

  const sortedConversations = computed(() => {
    const getTimestamp = (conv) => {
      const t = conv.lastMessageTime || conv.lastTime
      if (!t) return 0
      return typeof t === 'number' ? t : new Date(t).getTime()
    }
    const list = [...conversations.value]
    const withMessage = list.filter(c => getTimestamp(c) > 0)
    const withoutMessage = list.filter(c => getTimestamp(c) === 0)

    withMessage.sort((a, b) => getTimestamp(b) - getTimestamp(a))
    withoutMessage.sort((a, b) => {
      const aName = (a.name || '').toLowerCase()
      const bName = (b.name || '').toLowerCase()
      return aName.localeCompare(bName)
    })

    return [...withMessage, ...withoutMessage]
  })

  return {
    // 状态
    conversations,
    currentConversation,
    messages,
    isConnected,
    onlineUsers,
    
    // 计算属性
    totalUnreadCount,
    sortedConversations,
    
    // 方法
    connectWebSocket,
    disconnect,
    sendMessage,
    loadConversations,
    loadMessageHistory,
    loadHistoryMessages,
    setCurrentConversation,
    markMessagesAsRead
  }
})